import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class ImagePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Image widge',
        home: Scaffold(
            appBar: AppBar(title: Text("imagePage")),
            body: Center(
                child: Container(
                    width: 300.0,
                    height: 200.0,
                    color: Colors.lightBlue,
                    child: Image.network(
                      "https://flutter.cn/images/flutter-lockup-1caf6476beed76adec3c477586da54de6b552b2f42108ec5bc68dc63bae2df75.png",
                      color: Colors.greenAccent,
                      colorBlendMode: BlendMode.darken,
                      repeat: ImageRepeat.repeat,
                    )))));
  }
}

class TextPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "Text widget",
        home: Scaffold(
            appBar: AppBar(title: Text("textPage")),
            body: Center(
              child: Container(
                width: 200.0,
                height: 200.0,
                padding: const EdgeInsets.all(10.0),
                margin: const EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 30.0),
                decoration: BoxDecoration(
                    color: Colors.lightBlue,
                    gradient: const LinearGradient(colors: [
                      Colors.lightBlue,
                      Colors.greenAccent,
                      Colors.purple
                    ]),
                    border: Border.all(
                        color: Colors.red,
                        width: 1.0,
                        style: BorderStyle.solid),
                    borderRadius: BorderRadius.all(Radius.circular(10.0))),
                alignment: Alignment.center,
                // color:Colors.lightBlue,  注意：color 不能和 decoration 同时设置
                child: Text("Flutter之从零到一的基本组件练习",
                    textAlign: TextAlign.center,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 25.0,
                      fontStyle: FontStyle.italic,
                      color: Color.fromARGB(255, 255, 150, 150),
                      decoration: TextDecoration.underline,
                      decorationStyle: TextDecorationStyle.wavy,
                    )),
              ),
            )));
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
      //路由表定义
      routes: {
        "textPage": (context) => TextPage(),
        "imagePage": (context) => ImagePage(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home pages of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  @mustCallSuper
  void initState() {
    print("initState");
    super.initState();
    WidgetsBinding.instance?.addObserver(this); // 注册监听器
  }

  /*
  *初始化时，在initState之后立刻调用
  *当State的依赖关系发生变化时，会触发此接口被调用
  */
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print("page1 didChangeDependencies......");
  }

  @override
  void setState(VoidCallback fn) {
    print("setState");
    super.setState(fn);
  }

//状态改变的时候会调用该方法,比如父类调用了setState
  @override
  void didUpdateWidget(covariant MyHomePage oldWidget) {
    print("didUpdateWidget");
    super.didUpdateWidget(oldWidget);
  }

  //当State对象从树中被移除时，会调用此回调
  @override
  void deactivate() {
    print("deactivate");
    super.deactivate();
  }

  //当State对象从树中被永久移除时调用；通常在此回调中释放资源
  @override
  void dispose() {
    print("dispose");
    super.dispose();
    WidgetsBinding.instance?.removeObserver(this); // 移除监听器
  }

  //监听App生命周期回调
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    print("$state");
    if (state == AppLifecycleState.resumed) {
      //do sth
    }
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    print("build");
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            MaterialButton(
                color: Colors.blue,
                textColor: Colors.white,
                onPressed: () {
                  print('pressed');
                  //MaterialPageRoute   CupertinoPageRoute
                  Navigator.push(context, MaterialPageRoute(builder: (context) {
                    return TextPage();
                  }));
                },
                child: Text("goto textPage")),
            MaterialButton(
                child: Text("goto textPage by routes(路由表)"),
                color: Colors.blue,
                textColor: Colors.white,
                onPressed: () {
                  Navigator.pushNamed(context, "textPage");
                }),
            MaterialButton(
                child: Text("goto imagePage by routes(路由表)"),
                color: Colors.blue,
                textColor: Colors.white,
                onPressed: () {
                  Navigator.pushNamed(context, "imagePage");
                }),
            Text(
              '点击次数:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
